<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Think;
use Think\Cache;
use Org\Util\oauth2\init;

class UserAccesstoken {
	
	function execute()
	{
		$context = Think::instance('Think\Context');
		$log_info = array();
		$log_info['action'] = 'begin';
		$log_info['request'] = array($_GET, $_POST);
		\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
		//获取请求的token
		$token = $context->cookie('access_token') ? $context->cookie('access_token') : $context->access_token;
		//验证token
		if (empty($token))
		{
			$log_info = array();
			$log_info['action'] = 'check';
			$log_info['action_result'] = 'fail';
			$log_info['request'] = array($_GET, $_POST);
			\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
			$context->code_str = array('error' => 'invalid_request');
		}
		try
		{
		    $redis =  Cache::singleton('redis');
			$token_stored = $redis->get($token);
		}
		catch(Exception $ex)
		{
			$log_info = array();
			$log_info['action'] = 'Redis';
			$log_info['action_result'] = 'fail';
			$log_info['request'] = array($_GET, $_POST);
			\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
			$context->code_str = array('error' => 'temporarily_unavailable');
		}
		if(!$token_stored)
		{
			$log_info = array();
			$log_info['action'] = 'token_stored';
			$log_info['action_result'] = 'fail';
			$log_info['request'] = array($_GET, $_POST);
			\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
			$context->code_str = array('error' => 'expired_token');
		}
		if($token_stored['expires'] < time())
		{
			$log_info = array();
			$log_info['action'] = 'expires';
			$log_info['action_result'] = 'fail';
			$log_info['request'] = array($_GET, $_POST);
			\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
			$context->code_str = array('error' => 'expired_token');
		}

		$log_info['action'] = 'end';
		$log_info['action_result'] = 'succ';
		$log_info['user_id'] = $token_stored['user_id'];
		$log_info['token_stored'] = $token_stored;
		\Logger::getLogger('api.filter.app')->apps('useraccesstoken')->info($log_info);
		$context->userId = $token_stored['user_id'];
	}

}
